<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\input\Argument;
use think\console\Output;
use think\facade\Env;
use think\Db;
use app\common\model\Admin;
use app\common\model\AdminOauth;
use app\common\model\AdminGroup;
use app\common\model\AdminRule;
use Exception;
use think\Container;
use Thinkadx\Oauth2\Main as Oauth2Main;

class Thinkadx extends Command
{
    protected function configure() {
        // 指令配置
        $this->setName('thinkadx')
        ->addOption('init', null, Option::VALUE_REQUIRED, 'init action')
        ->addOption('action', null, Option::VALUE_REQUIRED, 'action name')
        ->setDescription('thinkadx');
    }

    protected function execute(Input $input, Output $output)
    {
        $result = '';
        if($input->hasOption('init')) {
            $initType = $input->getOption('init');
            switch($initType) {
                case 'mysql-data' :
                        // 检测是否可以导入
                        try {
                            if(Admin::count() > 0) {
                                throw new \think\Exception('init fail, data exists', 10006);
                            }
                        } catch(\think\exception\PDOException $e) {
                            throw new \think\Exception('init fail, not table exists', 10006);
                        }   

                        // 创建数据
                        $this->writeDatebaseData();
                        $output->writeln('data write success...');
                        // 创建系统资源
                        $output->writeln('create resources ...');
                        $this->createDefaultIcon($output);

                        $output->writeln('init success!!!');
                    break;
            }
        } else if($input->hasOption('action')) {
            // 操作
            $initType = $input->getOption('action');
            switch($initType) {
                case 'empty_expired_cache' : 
                        // 清空过期缓存
                        $path = Container::get('app')->getRuntimePath() . 'cache' . DIRECTORY_SEPARATOR;
                        $files = (array) glob($path . (config('cache.default.prefix') ? config('cache.default.prefix') . DIRECTORY_SEPARATOR : '') . '*');
                        foreach ($files as $path) {
                            if (is_dir($path)) {
                                $matches = glob($path . DIRECTORY_SEPARATOR . '*.php');
                                array_map('del_expired_file_cache', $matches);
                                // 文件夹为空则删除
                                if(empty(array_diff(scandir($path),array('..','.')))) {
                                    rmdir($path);
                                }
                            } else {
                                del_expired_file_cache($path);
                            }
                        }
                        $output->writeln('action success');
                    break;
                case 'kill_expired_token' :
                        // 删除过期token
                        try {
                            Oauth2Main::taskKillNullToken();
                            $output->writeln('action success');
                        } catch(\Exception $e) {
                            // 发送邮件
                            throw new \think\Exception('Kill_expired_token fail', 10006);
                        }
                    break;
            }
        }

    }

    protected function createDefaultIcon($output) {
        $systemDefaultIconDir = Env::get('root_path') . 'public/uploads/system_default_icon/';
        if(!is_dir($systemDefaultIconDir)) {
            mkdir($systemDefaultIconDir, '0744', true);
        }

        // 默认头像
        $defaultUserAvatarbase = '';
        $file = $this->createBaseFile('avatar', $defaultUserAvatarbase, $systemDefaultIconDir);

        // 菜单-系统设置
        $defaultUserAvatarbase = '';
        $file = $this->createBaseFile('system_setup', $defaultUserAvatarbase, $systemDefaultIconDir);

        // 菜单-管理员管理
        $defaultUserAvatarbase = '';
        $file = $this->createBaseFile('admin_manage', $defaultUserAvatarbase, $systemDefaultIconDir);

        $output->writeln($systemDefaultIconDir);
    }


    /**
     * 创建文件
     * @param string $name 文件名
     * @param string $content 文件内容
     * @param string $path 文件路径
     * @return void
     */
    protected function createBaseFile($name, $content, $path) {
        //正则匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $content, $result)) {
            $type = $result[2];  //获取图片格式
            $new_file = $path . $name . ".{$type}";
            file_put_contents($new_file, base64_decode(str_replace($result[1], '', $content)));
        }
    }


    // 往数据库写数据
    protected function writeDatebaseData() {
        $timeStr = time();

        // admin
        Db::name('admin')->insert([
            'avatar'        => '',
            'group_id'      => 1,
            'nickname'      => '超级管理员',
            'access'        => 'admin',
            'create_time'   => $timeStr,
        ]);

        // admin_group
        Db::name('admin_group')->insert([
            'name'          => '所有权限',
            'status'        => '1',
            'rules'         => '1',
            'create_time'   => $timeStr,
        ]);

        // admin_menu
        Db::name('admin_menu')->insertAll([
            [
                'icon'        => '/uploads/system_default_icon/system_setup.png',
                'title'       => '系统设置',
                'module'      => '',
                'controller'  => '',
                'action'      => '',
                'status'      => 1,
                'father_id'   => 0,
                'create_time' => $timeStr,
            ],
            [
                'icon'        => '',
                'title'       => '菜单设置',
                'module'      => 'admin',
                'controller'  => 'menu',
                'action'      => 'index',
                'status'      => 1,
                'father_id'   => 1,
                'create_time' => $timeStr,
            ],
            [
                'icon'        => '/uploads/system_default_icon/admin_manage.png',
                'title'       => '管理员管理',
                'module'      => '',
                'controller'  => '',
                'action'      => '',
                'status'      => 1,
                'father_id'   => 0,
                'create_time' => $timeStr,
            ],
            [
                'icon'        => '',
                'title'       => '管理员列表',
                'module'      => 'admin',
                'controller'  => 'admin_user',
                'action'      => 'index',
                'status'      => 1,
                'father_id'   => 3,
                'create_time' => $timeStr,
            ],
            [
                'icon'        => '',
                'title'       => '管理员分组',
                'module'      => 'admin',
                'controller'  => 'admin_group',
                'action'      => 'index',
                'status'      => 1,
                'father_id'   => 3,
                'create_time' => $timeStr,
            ],
            [
                'icon'        => '',
                'title'       => '分组规则',
                'module'      => 'admin',
                'controller'  => 'admin_rule',
                'action'      => 'index',
                'status'      => 1,
                'father_id'   => 3,
                'create_time' => $timeStr,
            ],
            [
                'icon'        => '',
                'title'       => '系统配置',
                'module'      => 'admin',
                'controller'  => 'config',
                'action'      => 'index',
                'status'      => 1,
                'father_id'   => 1,
                'create_time' => $timeStr,
            ],
            [
                'icon'        => '',
                'title'       => '管理员操作日志',
                'module'      => 'admin',
                'controller'  => 'admin_log',
                'action'      => 'index',
                'status'      => 1,
                'father_id'   => 1,
                'create_time' => $timeStr,
            ]
        ]);

        // admin_oauth
        Db::name('admin_oauth')->insert([
            'admin_id'          =>  1,
            'identifier'        => '3b1f1f4eafccab421abac7b9bfe056b6',
            'unique_identifier' => '738607423',
            'oauth_type'        => 'password',
            'port_type'         => 'api',
            'access_token'      => '',
            'refresh_token'              => '',
            'last_use_access_token'      => '',
            'refresh_token_create_time'  => '',
            'access_token_create_time'   => '',
            'create_time'                => $timeStr,
        ]);

        // admin_rule
        Db::name('admin_rule')->insert([
            'rule'          =>  '*/*:*',
            'des'           => '所有权限',
            'create_time'   => $timeStr,
        ]);

        // admin_rule
        Db::name('config')->insertAll([
            [
                'name'            =>  '管理员访问令牌周期',
                'alias'           => 'admin_access_token_time_out',
                'type'            => 'system',
                'value'           => '7200',
                'description'     => '秒位单位',
            ],
            [
                'name'            =>  '管理员刷新令牌周期',
                'alias'           => 'admin_refresh_token_time_out',
                'type'            => 'system',
                'value'           => '604800',
                'description'     => '秒位单位',
            ],
            [
                'name'            =>  '后台系统名称',
                'alias'           => 'admin_system_name',
                'type'            => 'system',
                'value'           => '某某管理系统',
                'description'     => '后台系统名称',
            ],
        ]);

        // admin_api
        Db::name('admin_api')->insert([
            'appid'               => 'xb4nBB6ZfEN7njAnlJHMRuR8',
            'appsecret'           => 'u6ucLCg9RWXRDm6TiEeYBhHK',
            'status'              => '1',
            'update_time'         => $timeStr,
            'create_time'         => $timeStr
        ]);
    }

}
